﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class DealerTarget : System.Web.UI.Page
    {
        #region Fields
        //private static GeneralFunctions GF = null;
        private string TblLineName = "tbl_EmpTarget";
        private string HeaderKeyName = "SlpCode";
        private string CurrentPageUrl = "/Business/DataCenter/EmployeeTarget.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }

                if (!IsPostBack)
                {
                    ClearScreen();

                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    Session["DLGF"] = GF;

                    String dealerId = Request.QueryString["dealer_id"];
                    String dateTarget = Request.QueryString["date_target"];
                    if (!string.IsNullOrEmpty(dateTarget))
                    {
                        LoadData(dealerId, dateTarget, "0");
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                   
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["EmpTargetTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No='" + lblNo.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["No"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["No"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvSO.EditIndex = -1;
                    BindData((DataTable)Session["EmpTargetTable"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    //DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblIncPmt = (DataTable)Session["IncPmtTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            //this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text; 
                            //this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            //this.txtCntctName.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;
                            Session["ChosenBP"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string incPmtId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            //LoadData(incPmtId, ((ulong)DocType.INCOMING).ToString());
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        public DataTable _collectData()
        {
            try
            {
                DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];

                DataTable dt = new DataTable("tbl_DealerTarget");
                dt.Columns.Add("CardCode");
                dt.Columns.Add("Model");
                dt.Columns.Add("Product");
                dt.Columns.Add("Comments");
                dt.Columns.Add("DateTarget");
                dt.Columns.Add("QtyTarget");
                dt.Columns.Add("internal_id");
                dt.Columns.Add("PlanType");

                DataRow rowNew = null;
                Double decQty = 0;
                int liID = 0;
                String lsQty = "0", lsID = "0";

                foreach (DataRow dr in tblDealerTarget.Rows)
                {
                    if (dr["CardCode"].ToString().Length > 0)
                    {
                        for (int i = 1; i <= 12; i++)
                        {
                            rowNew = dt.NewRow();
                            rowNew["CardCode"] = dr["CardCode"];
                            rowNew["Model"] = dr["Model"];
                            rowNew["Product"] = dr["Product"];
                            rowNew["Comments"] = txtRemarks.Text.Trim();
                            rowNew["DateTarget"] = (i < 10 ? "0" + i.ToString() : i.ToString()) + "/01/" + txtStartMonthYear.Text;
                            // Parse Qty
                            lsQty = dr["QtyTarget_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                            decQty = Double.Parse((String.IsNullOrEmpty(lsQty) || lsQty.Equals("0")) ? "0" : lsQty);
                            rowNew["QtyTarget"] = decQty;
                            // Parse ID
                            lsID = dr["internal_id_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                            liID = int.Parse((String.IsNullOrEmpty(lsID) || lsID.Equals("0")) ? "0" : lsID);
                            rowNew["internal_id"] = liID;
                            rowNew["PlanType"] = dr["PlanType"];
                            dt.Rows.Add(rowNew);
                        }
                    }
                }
                
                return dt;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return null;
            }
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["DLGF"];
            DataTable dt = CreateDealerTargetTable();

            if (dtContent != null)
            {
                string lsModel = String.Empty, lsProduct = String.Empty;
                DataRow newRow = null;

                foreach (DataRow dr in dtContent.Rows)
                {
                    Double decQty = Double.Parse(String.IsNullOrEmpty(dr["QtyTarget"].ToString()) ? "0" : dr["QtyTarget"].ToString());
                    int liinternal_id = int.Parse(String.IsNullOrEmpty(dr["internal_id"].ToString()) ? "0" : dr["internal_id"].ToString());

                    //if (CardCode != dr["CardCode"].ToString() || lsModel != dr["Model"].ToString() || lsProduct != dr["Product"].ToString())
                    if (lsModel != dr["Model"].ToString() || lsProduct != dr["Product"].ToString())
                    {
                        if (newRow != null) dt.Rows.Add(newRow);
                        newRow = dt.NewRow();
                        newRow["No"] = (dt.Rows.Count + 1);
                        newRow["CardCode"] = ddlDealer.SelectedValue;
                        newRow["Model"] = lsModel = dr["Model"].ToString();
                        newRow["Product"] = lsProduct = dr["Product"].ToString();
                        newRow["Comments"] = dr["Comments"].ToString();
                        newRow["Total"] = dr["Total"].ToString();
                        newRow["QtyTarget_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["internal_id_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = liinternal_id;
                        newRow["PlanType"] = ddlType.SelectedValue;
                    }
                    else
                    {
                        newRow["QtyTarget_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["internal_id_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = liinternal_id;
                    }
                }
                if (newRow != null) dt.Rows.Add(newRow);
            }
            
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable tblDealerTarget = _collectData();
                if (tblDealerTarget == null || tblDealerTarget.Rows.Count < 1) return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateDealerTarget(Utils.AppConstants.DEALER, tblDealerTarget);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
                //if (_isPO == "1")
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
                //}
                //else
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
                //}
                //if (error.Length == 0)
                //{
                //    this.lblError.Text = "Operation complete successful!";
                //    DisableControl();
                //}
                //else
                //{
                //    this.lblError.Text = error;
                //}
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        protected void LoadData(string dealer_id, string date_target, string plantype)
        {
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetDealerTarget(Utils.AppConstants.DEALER, dealer_id, date_target, plantype);

            if (returnDoc == null || returnDoc.Tables.Count <= 0 )
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            //DataTable dtContents = returnDoc.Tables[0];

            DataTable dtHeader = returnDoc.Tables[0];
            if (returnDoc.Tables[0].Rows.Count > 0)
            {
                DataRow dr = dtHeader.Rows[0];
                txtRemarks.Text = dr["Comments"].ToString();
            }
            DataTable tblDealerTarget = BuildContents(dtHeader);
            BindData(tblDealerTarget);
        }

        protected void LoadDefault()
        {
            DataTable dtDealers = ((GeneralFunctions)Session["DLGF"]).GetDealers(Utils.AppConstants.VSM, Session[Utils.AppConstants.ID_Dealer].ToString(), "(104)");
            ddlDealer.DataSource = dtDealers;
            ddlDealer.DataValueField = "CardCode";
            ddlDealer.DataTextField = "CardName";
            ddlDealer.DataBind();
            //ListItem item = new ListItem("", "-1");
           // ddlDealer.Items.Insert(0, item);
            
            // Load detail
            BindData(CreateDealerTargetTable());
        }

        private DataTable CreateDealerTargetTable()
        {
            DataTable tblEmpTarget = new DataTable("tbl_DealerTarget");
            tblEmpTarget = new DataTable("tbl_DealerTarget");
            tblEmpTarget.Columns.Add("No");
            
            tblEmpTarget.Columns.Add("CardCode");
            tblEmpTarget.Columns.Add("Model");
            tblEmpTarget.Columns.Add("Product");
            tblEmpTarget.Columns.Add("Comments");
            tblEmpTarget.Columns.Add("PlanType");
            tblEmpTarget.Columns.Add("QtyTarget_01");
            tblEmpTarget.Columns.Add("QtyTarget_02");
            tblEmpTarget.Columns.Add("QtyTarget_03");
            tblEmpTarget.Columns.Add("QtyTarget_04");
            tblEmpTarget.Columns.Add("QtyTarget_05");
            tblEmpTarget.Columns.Add("QtyTarget_06");
            tblEmpTarget.Columns.Add("QtyTarget_07");
            tblEmpTarget.Columns.Add("QtyTarget_08");
            tblEmpTarget.Columns.Add("QtyTarget_09");
            tblEmpTarget.Columns.Add("QtyTarget_10");
            tblEmpTarget.Columns.Add("QtyTarget_11");
            tblEmpTarget.Columns.Add("QtyTarget_12");

            tblEmpTarget.Columns.Add("internal_id_01");
            tblEmpTarget.Columns.Add("internal_id_02");
            tblEmpTarget.Columns.Add("internal_id_03");
            tblEmpTarget.Columns.Add("internal_id_04");
            tblEmpTarget.Columns.Add("internal_id_05");
            tblEmpTarget.Columns.Add("internal_id_06");
            tblEmpTarget.Columns.Add("internal_id_07");
            tblEmpTarget.Columns.Add("internal_id_08");
            tblEmpTarget.Columns.Add("internal_id_09");
            tblEmpTarget.Columns.Add("internal_id_10");
            tblEmpTarget.Columns.Add("internal_id_11");
            tblEmpTarget.Columns.Add("internal_id_12");
            tblEmpTarget.Columns.Add("Total");
            return tblEmpTarget;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["DealerTargetTable"] = tblData;
            this.grvSO.DataSource = tblData;
            this.grvSO.DataBind();
        }

        protected void ClearScreen()
        {
            txtRemarks.Text = String.Empty;
            BindData(CreateDealerTargetTable());
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnSave.Enabled =
                    btnCancel.Enabled = 
                    btnAddItems.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnAddItems.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "C";
                    break;

                case "Close":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnAddItems.Enabled = false;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvSO.PageIndex = e.NewPageIndex;
            DataTable tblEmpTarget = (DataTable)Session["DealerTargetTable"];
            BindData(tblEmpTarget);
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                if (this.hdnStatus.Value == "C")
                {
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                //
                GeneralFunctions GF = (GeneralFunctions)Session["DLGF"];
                // Default Dealer DB: Load Employees 
                DropDownList ddlDealerName = (DropDownList)e.Row.FindControl("ddlDealerName");
                HiddenField hdnCarsCode = (HiddenField)e.Row.FindControl("hdnCarsCode");

                if (ddlDealerName != null && hdnCarsCode != null)
                {
                    DataTable dtDealer = GF.GetDealers(Utils.AppConstants.VSM, ddlDealer.SelectedValue.Equals("-1") ? "" : ddlDealer.SelectedValue, "(104)");
                    ddlDealerName.DataSource = dtDealer;
                    ddlDealerName.DataTextField = "CardName";
                    ddlDealerName.DataValueField = "CardCode";
                    ddlDealerName.DataBind();
                    //ddlDealerName.Items.Insert(0, new ListItem("", "-1"));
                    ddlDealerName.SelectedValue = hdnCarsCode.Value;
                }
                
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                HiddenField hdnModel = (HiddenField)e.Row.FindControl("hdnModel");
                if (ddlModel != null && hdnModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    //ddlModel.Items.Insert(0, "");
                    if (hdnModel != null) ddlModel.SelectedValue = hdnModel.Value;
                }

                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                HiddenField hdnProduct = (HiddenField)e.Row.FindControl("hdnProduct");
                if (ddlProduct != null && hdnModel != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, hdnModel.Value);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    //ddlProduct.Items.Insert(0, "");
                    if (hdnProduct != null) ddlProduct.SelectedValue = hdnProduct.Value;
                }

                // 
                double qty1 = 0, qty2 = 0, qty3 = 0, qty4 = 0, qty5 = 0, qty6 = 0, qty7 = 0, qty8 = 0, qty9 = 0, qty10 = 0, qty11 = 0, qty12 = 0;
                TextBox txtQty01 = (TextBox)e.Row.FindControl("txtQuantity_01");
                TextBox txtQty02 = (TextBox)e.Row.FindControl("txtQuantity_02");
                TextBox txtQty03 = (TextBox)e.Row.FindControl("txtQuantity_03");
                TextBox txtQty04 = (TextBox)e.Row.FindControl("txtQuantity_04");
                TextBox txtQty05 = (TextBox)e.Row.FindControl("txtQuantity_05");
                TextBox txtQty06 = (TextBox)e.Row.FindControl("txtQuantity_06");
                TextBox txtQty07 = (TextBox)e.Row.FindControl("txtQuantity_07");
                TextBox txtQty08 = (TextBox)e.Row.FindControl("txtQuantity_08");
                TextBox txtQty09 = (TextBox)e.Row.FindControl("txtQuantity_09");
                TextBox txtQty10 = (TextBox)e.Row.FindControl("txtQuantity_10");
                TextBox txtQty11 = (TextBox)e.Row.FindControl("txtQuantity_11");
                TextBox txtQty12 = (TextBox)e.Row.FindControl("txtQuantity_12");
                Label lblTotal = (Label)e.Row.FindControl("lblTotal");

                if (lblTotal != null)
                {
                    if (txtQty01 != null) double.TryParse(txtQty01.Text.Trim(), out qty1);
                    if (txtQty02 != null) double.TryParse(txtQty02.Text.Trim(), out qty2);
                    if (txtQty03 != null) double.TryParse(txtQty03.Text.Trim(), out qty3);
                    if (txtQty04 != null) double.TryParse(txtQty04.Text.Trim(), out qty4);

                    if (txtQty05 != null) double.TryParse(txtQty05.Text.Trim(), out qty5);
                    if (txtQty06 != null) double.TryParse(txtQty06.Text.Trim(), out qty6);
                    if (txtQty07 != null) double.TryParse(txtQty07.Text.Trim(), out qty7);
                    if (txtQty08 != null) double.TryParse(txtQty08.Text.Trim(), out qty8);

                    if (txtQty09 != null) double.TryParse(txtQty09.Text.Trim(), out qty9);
                    if (txtQty10 != null) double.TryParse(txtQty10.Text.Trim(), out qty10);
                    if (txtQty11 != null) double.TryParse(txtQty11.Text.Trim(), out qty11);
                    if (txtQty12 != null) double.TryParse(txtQty12.Text.Trim(), out qty12);

                    lblTotal.Text = (qty1 + qty2 + qty3 + qty4 + qty5 + qty6 + qty7 + qty8 + qty9 + qty10 + qty11 + qty12).ToString();
                }

            }
        }

        protected void ddlDealerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;

                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlDealerName = (DropDownList)row.FindControl("ddlDealerName");

                Label lblNo = (Label)row.FindControl("lblNo");
                DataRow[] rupdate = tblDealerTarget.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["CardCode"] = (ddlDealerName != null ? ddlDealerName.SelectedValue : "-1");
                
                this.grvSO.EditIndex = -1;
                BindData(tblDealerTarget);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");

                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                HiddenField hdnModel = (HiddenField)row.FindControl("hdnModel");
                if (hdnModel != null) hdnModel.Value = ddlModel.SelectedValue;
                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = ((GeneralFunctions)Session["DLGF"]).GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    //ddlProduct.Items.Insert(0, "");

                    HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                    if (hdnProduct != null) hdnProduct.Value = ddlProduct.SelectedValue;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataRow[] rupdate = tblDealerTarget.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0)
                {
                    rupdate[0]["Model"] = (hdnModel != null ? hdnModel.Value : "-1");
                    rupdate[0]["Product"] = (ddlProduct != null ? ddlProduct.SelectedValue : "-1");
                    this.grvSO.EditIndex = -1;
                    BindData(tblDealerTarget);
                }

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                if (hdnProduct != null) hdnProduct.Value = ddlProduct.SelectedValue;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataRow[] rupdate = tblDealerTarget.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0)
                {
                    rupdate[0]["Product"] = (ddlProduct != null ? ddlProduct.SelectedValue : "-1");
                    this.grvSO.EditIndex = -1;
                    BindData(tblDealerTarget);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQtyTarget_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                // Get quantity
                TextBox txtQty01 = (TextBox)row.FindControl("txtQuantity_01");
                TextBox txtQty02 = (TextBox)row.FindControl("txtQuantity_02");
                TextBox txtQty03 = (TextBox)row.FindControl("txtQuantity_03");
                TextBox txtQty04 = (TextBox)row.FindControl("txtQuantity_04");
                TextBox txtQty05 = (TextBox)row.FindControl("txtQuantity_05");
                TextBox txtQty06 = (TextBox)row.FindControl("txtQuantity_06");
                TextBox txtQty07 = (TextBox)row.FindControl("txtQuantity_07");
                TextBox txtQty08 = (TextBox)row.FindControl("txtQuantity_08");
                TextBox txtQty09 = (TextBox)row.FindControl("txtQuantity_09");
                TextBox txtQty10 = (TextBox)row.FindControl("txtQuantity_10");
                TextBox txtQty11 = (TextBox)row.FindControl("txtQuantity_11");
                TextBox txtQty12 = (TextBox)row.FindControl("txtQuantity_12");
                // Get ID
                HiddenField hdnInternalID_01 = (HiddenField)row.FindControl("hdnInternalID_01");
                HiddenField hdnInternalID_02 = (HiddenField)row.FindControl("hdnInternalID_02");
                HiddenField hdnInternalID_03 = (HiddenField)row.FindControl("hdnInternalID_03");
                HiddenField hdnInternalID_04 = (HiddenField)row.FindControl("hdnInternalID_04");
                HiddenField hdnInternalID_05 = (HiddenField)row.FindControl("hdnInternalID_05");
                HiddenField hdnInternalID_06 = (HiddenField)row.FindControl("hdnInternalID_06");
                HiddenField hdnInternalID_07 = (HiddenField)row.FindControl("hdnInternalID_07");
                HiddenField hdnInternalID_08 = (HiddenField)row.FindControl("hdnInternalID_08");
                HiddenField hdnInternalID_09 = (HiddenField)row.FindControl("hdnInternalID_09");
                HiddenField hdnInternalID_10 = (HiddenField)row.FindControl("hdnInternalID_10");
                HiddenField hdnInternalID_11 = (HiddenField)row.FindControl("hdnInternalID_11");
                HiddenField hdnInternalID_12 = (HiddenField)row.FindControl("hdnInternalID_12");

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];

                if (tblDealerTarget != null)
                {
                    DataRow[] rupdate = tblDealerTarget.Select("No='" + lblNo.Text +"'");
                    if (rupdate.Length > 0)
                    {
                        // update qty
                        rupdate[0]["QtyTarget_01"] = (txtQty01 != null ? txtQty01.Text : "0");
                        rupdate[0]["QtyTarget_02"] = (txtQty02 != null ? txtQty02.Text : "0");
                        rupdate[0]["QtyTarget_03"] = (txtQty04 != null ? txtQty03.Text : "0");
                        rupdate[0]["QtyTarget_04"] = (txtQty04 != null ? txtQty04.Text : "0");
                        rupdate[0]["QtyTarget_05"] = (txtQty05 != null ? txtQty05.Text : "0");
                        rupdate[0]["QtyTarget_06"] = (txtQty06 != null ? txtQty06.Text : "0");
                        rupdate[0]["QtyTarget_07"] = (txtQty07 != null ? txtQty07.Text : "0");
                        rupdate[0]["QtyTarget_08"] = (txtQty08 != null ? txtQty08.Text : "0");
                        rupdate[0]["QtyTarget_09"] = (txtQty09 != null ? txtQty09.Text : "0");
                        rupdate[0]["QtyTarget_10"] = (txtQty10 != null ? txtQty10.Text : "0");
                        rupdate[0]["QtyTarget_11"] = (txtQty11 != null ? txtQty11.Text : "0");
                        rupdate[0]["QtyTarget_12"] = (txtQty12 != null ? txtQty12.Text : "0");
                        // update ID
                        rupdate[0]["internal_id_01"] = (hdnInternalID_01 != null ? hdnInternalID_01.Value : "0");
                        rupdate[0]["internal_id_02"] = (hdnInternalID_02 != null ? hdnInternalID_02.Value : "0");
                        rupdate[0]["internal_id_03"] = (hdnInternalID_03 != null ? hdnInternalID_03.Value : "0");
                        rupdate[0]["internal_id_04"] = (hdnInternalID_04 != null ? hdnInternalID_04.Value : "0");
                        rupdate[0]["internal_id_05"] = (hdnInternalID_05 != null ? hdnInternalID_05.Value : "0");
                        rupdate[0]["internal_id_06"] = (hdnInternalID_06 != null ? hdnInternalID_06.Value : "0");
                        rupdate[0]["internal_id_07"] = (hdnInternalID_07 != null ? hdnInternalID_07.Value : "0");
                        rupdate[0]["internal_id_08"] = (hdnInternalID_08 != null ? hdnInternalID_08.Value : "0");
                        rupdate[0]["internal_id_09"] = (hdnInternalID_09 != null ? hdnInternalID_09.Value : "0");
                        rupdate[0]["internal_id_10"] = (hdnInternalID_10 != null ? hdnInternalID_10.Value : "0");
                        rupdate[0]["internal_id_11"] = (hdnInternalID_11 != null ? hdnInternalID_11.Value : "0");
                        rupdate[0]["internal_id_12"] = (hdnInternalID_12 != null ? hdnInternalID_12.Value : "0");
                    }
                }

                this.grvSO.EditIndex = -1;
                BindData(tblDealerTarget);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tblDealerTarget = (DataTable)Session["DealerTargetTable"];
            if (tblDealerTarget == null) tblDealerTarget = CreateDealerTargetTable();

            DataRow rowNew = tblDealerTarget.NewRow();
            rowNew["No"] = (tblDealerTarget.Rows.Count + 1).ToString();
            rowNew["CardCode"] = ddlDealer.SelectedValue;
            rowNew["Model"] = "-1";
            rowNew["Product"] = "-1";
            rowNew["PlanType"] = ddlType.SelectedValue;
            rowNew["QtyTarget_01"] =
            rowNew["QtyTarget_02"] =
            rowNew["QtyTarget_03"] =
            rowNew["QtyTarget_04"] = 
            rowNew["QtyTarget_05"] =
            rowNew["QtyTarget_06"] =
            rowNew["QtyTarget_07"] =
            rowNew["QtyTarget_08"] = 
            rowNew["QtyTarget_09"] = 
            rowNew["QtyTarget_10"] =
            rowNew["QtyTarget_11"] = 
            rowNew["QtyTarget_12"] = 0;
            rowNew["internal_id_01"] =
            rowNew["internal_id_02"] =
            rowNew["internal_id_03"] =
            rowNew["internal_id_04"] =
            rowNew["internal_id_05"] =
            rowNew["internal_id_06"] =
            rowNew["internal_id_07"] =
            rowNew["internal_id_08"] =
            rowNew["internal_id_09"] =
            rowNew["internal_id_10"] =
            rowNew["internal_id_11"] =
            rowNew["internal_id_12"] = 0;
            tblDealerTarget.Rows.Add(rowNew);
            BindData(tblDealerTarget);
        }

        private DataTable datatable4Exp()
        {
            DataTable dtRecords = new DataTable();
            dtRecords.Columns.Add(new DataColumn("No", typeof(System.Int32)));          // 0
            dtRecords.Columns.Add(new DataColumn("DealerCode", typeof(System.String))); // 1  
            dtRecords.Columns.Add(new DataColumn("Model", typeof(System.String)));      // 2
            dtRecords.Columns.Add(new DataColumn("Product", typeof(System.String)));// 3
            dtRecords.Columns.Add(new DataColumn("Jan.", typeof(System.Int32)));        // 4
            dtRecords.Columns.Add(new DataColumn("Feb.", typeof(System.Int32)));        // 5
            dtRecords.Columns.Add(new DataColumn("Mar.", typeof(System.Int32)));        // 6
            dtRecords.Columns.Add(new DataColumn("Apr.", typeof(System.Int32)));        // 7
            dtRecords.Columns.Add(new DataColumn("May", typeof(System.Int32)));         // 8
            dtRecords.Columns.Add(new DataColumn("Jun.", typeof(System.Int32)));        // 9
            dtRecords.Columns.Add(new DataColumn("Jul.", typeof(System.Int32)));        // 10
            dtRecords.Columns.Add(new DataColumn("Aug.", typeof(System.Int32)));        // 11
            dtRecords.Columns.Add(new DataColumn("Sep.", typeof(System.Int32)));        // 12
            dtRecords.Columns.Add(new DataColumn("Oct.", typeof(System.Int32)));        // 13
            dtRecords.Columns.Add(new DataColumn("Nov.", typeof(System.Int32)));        // 14
            dtRecords.Columns.Add(new DataColumn("Dec.", typeof(System.Int32)));        // 15

            DataTable dtBPPlan = (DataTable)Session["DealerTargetTable"];
            foreach (DataRow dr in dtBPPlan.Rows)
            {
                DataRow newRow = dtRecords.NewRow();
                newRow["No"] = dr["No"];
                newRow["DealerCode"] = dr["CardCode"].ToString();
                newRow["Model"] = dr["Model"].ToString();
                newRow["Product"] = dr["Product"].ToString();
                newRow["Jan."] = dr["QtyTarget_01"];
                newRow["Feb."] = dr["QtyTarget_02"];
                newRow["Mar."] = dr["QtyTarget_03"];
                newRow["Apr."] = dr["QtyTarget_04"];
                newRow["May"] = dr["QtyTarget_05"];
                newRow["Jun."] = dr["QtyTarget_06"];
                newRow["Jul."] = dr["QtyTarget_07"];
                newRow["Aug."] = dr["QtyTarget_08"];
                newRow["Sep."] = dr["QtyTarget_09"];
                newRow["Oct."] = dr["QtyTarget_10"];
                newRow["Nov."] = dr["QtyTarget_11"];
                newRow["Dec."] = dr["QtyTarget_12"];
                dtRecords.Rows.Add(newRow);
            }

            return dtRecords;
        }

        private bool ImportValidation()
        {

            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a .csv file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if (!lsFileExtension.Equals(".csv"))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        private void ImportData()
        {
            DataTable tblBPPlan = (DataTable)Session["DealerTargetTable"];
            DataTable newBPPlan = tblBPPlan.Clone();
            GeneralFunctions GF = (GeneralFunctions)Session["DLGF"];

            for (int x = 1; x < GF.FileLines.Count; x++)
            {
                string[] rowData = GF.FileLines[x].ToString().Split(',');
                DataRow dr = newBPPlan.NewRow();
                dr["No"] = rowData[0];
                dr["CardCode"] = rowData[1].ToString().Replace("'", string.Empty);
                dr["Model"] = rowData[2].ToString().Replace("'", string.Empty);
                dr["Product"] = rowData[3];
                dr["Comments"] = txtRemarks.Text.Trim();
                dr["PlanType"] = ddlType.SelectedValue;
                dr["QtyTarget_01"] = rowData[4];
                dr["QtyTarget_02"] = rowData[5];
                dr["QtyTarget_03"] = rowData[6];
                dr["QtyTarget_04"] = rowData[7];
                dr["QtyTarget_05"] = rowData[8];
                dr["QtyTarget_06"] = rowData[9];
                dr["QtyTarget_07"] = rowData[10];
                dr["QtyTarget_08"] = rowData[11];
                dr["QtyTarget_09"] = rowData[12];
                dr["QtyTarget_10"] = rowData[13];
                dr["QtyTarget_11"] = rowData[14];
                dr["QtyTarget_12"] = rowData[15];
                dr["internal_id_01"] = 0;
                dr["internal_id_02"] = 0;
                dr["internal_id_03"] = 0;
                dr["internal_id_04"] = 0;
                dr["internal_id_05"] = 0;
                dr["internal_id_06"] = 0;
                dr["internal_id_07"] = 0;
                dr["internal_id_08"] = 0;
                dr["internal_id_09"] = 0;
                dr["internal_id_10"] = 0;
                dr["internal_id_11"] = 0;
                dr["internal_id_12"] = 0;
                newBPPlan.Rows.Add(dr);
            }

            BindData(newBPPlan);
            //Session["DealerTargetTable"] = newBPPlan;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData(ddlDealer.SelectedValue.Equals("-1") ? "" : ddlDealer.SelectedValue, txtStartMonthYear.Text, ddlType.SelectedValue);
        }

        protected void btnGetTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = datatable4Exp();

                if (dt != null)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=BPPlan.csv");
                    Response.ContentType = "text/csv";
                    int iColCount = dt.Columns.Count;

                    for (int i = 0; i < iColCount; i++)
                    {
                        Response.Write("\"" + dt.Columns[i] + "\"");
                        if (i < iColCount - 1) Response.Write(",");
                    }

                    Response.Write(Environment.NewLine);
                    // Now write all the rows.
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (i == 1 || i == 2)
                                if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + "'" + dt.Rows[x][i].ToString() + "\"");
                            else
                                if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");

                            if (i < iColCount - 1) Response.Write(",");
                        }
                        Response.Write(Environment.NewLine);
                    }
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!ImportValidation()) return;
            // Reading .csv file
            string errMsg = ((GeneralFunctions)Session[""]).ReadFile(this.FileUploadControl.PostedFile.InputStream);
            if (string.IsNullOrEmpty(errMsg))
            {
                ImportData();
            }
            else
            {
                Session["errorMessage"] = errMsg;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
            }
        }
    }
}